import multiprocessing
import os
import sys
from datetime import datetime

def setup_logging(name):
    """设置日志输出格式"""
    def log_message(message):
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(f"[{timestamp}] [{name}] {message}")
    return log_message

def run_process(script_path, command, name):
    """在子进程中运行命令"""
    log = setup_logging(name)
    log(f"开始启动 {name} 进程")
    
    try:
        # 直接使用 Python 解释器运行脚本
        os.system(f"{sys.executable} {script_path} {command}")
    except Exception as e:
        log(f"进程执行出错: {e}")
    finally:
        log(f"{name} 进程已退出")

def main():
    # 获取脚本所在目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    proxy_pool_script = os.path.join(script_dir, "proxyPool.py")
    
    # 创建日志函数
    log = setup_logging("Main")
    log("正在启动代理池服务...")

    try:
        # 创建服务器进程
        server_process = multiprocessing.Process(
            target=run_process,
            args=(proxy_pool_script, "server", "Server"),
            name="ProxyPool-Server"
        )

        # 创建调度器进程
        scheduler_process = multiprocessing.Process(
            target=run_process,
            args=(proxy_pool_script, "schedule", "Scheduler"),
            name="ProxyPool-Scheduler"
        )

        # 启动进程
        server_process.start()
        log(f"服务器进程已启动 (PID: {server_process.pid})")
        
        scheduler_process.start()
        log(f"调度器进程已启动 (PID: {scheduler_process.pid})")

        # 等待进程结束
        server_process.join()
        scheduler_process.join()

    except KeyboardInterrupt:
        log("收到终止信号，正在关闭服务...")
        server_process.terminate()
        scheduler_process.terminate()
        server_process.join()
        scheduler_process.join()
        log("所有进程已关闭")
    except Exception as e:
        log(f"启动服务时出错: {e}")
        raise

if __name__ == "__main__":
    # 确保在 Windows 下使用 spawn 方式启动进程
    multiprocessing.set_start_method('spawn', force=True)
    main()